package org.easy.minimaxi;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.annotation.JSONField;
import org.easy.core.exception.BizRuntimeException;
import org.easy.core.util.HttpUtil;
import org.easy.core.util.ObjectUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 通用方法封装工具类
 */
@Slf4j
@AllArgsConstructor
public class MinimaxiClient {

    private static String COMMIT_URI = "https://api.minimax.chat/v1/video_generation";

    private String apiKey;

    public String commit(String fileUrl, String prompt) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Bearer " + apiKey);

        Map<String, String> body = new HashMap<>();
        body.put("model", "I2V-01");
        body.put("prompt", prompt);
        body.put("first_frame_image", fileUrl);

        log.info("MinimaxiClient commit  {} {} {}", COMMIT_URI, headers, body);
        String response = HttpUtil.postJson(COMMIT_URI, headers, body);
        JSONObject jsonObject = JSON.parseObject(response);
        String taskId = jsonObject.getString("task_id");
        if (ObjectUtil.isEmpty(taskId)) {
            log.error("MinimaxiClient commit taskId is empty,{}", response);
            throw new RuntimeException("task_id is null" + response);
        }
        return taskId;
    }

    private static String QUERY_URI = "https://api.minimax.chat/v1/query/video_generation?task_id=";

    private static String RETRIEVE_URI = "https://api.minimax.chat/v1/files/retrieve?file_id=";

    public String query(String taskId) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Bearer " + apiKey);
        log.info("MinimaxiClient commit  {} {} ", QUERY_URI, headers);
        String response = HttpUtil.sendGet(QUERY_URI + taskId, headers, null);
        TaskInfo taskInfo = JSON.parseObject(response, TaskInfo.class);
        if (taskInfo.getStatus().equals("Success")) {
            String file_response = HttpUtil.sendGet(RETRIEVE_URI + taskInfo.getFileId(), headers, null);
            JSONObject jsonObject = JSON.parseObject(file_response);
            return jsonObject.getJSONObject("file").getString("download_url");
        }

        if (taskInfo.getStatus().equals("Fail")) {
            log.error("MinimaxiClient commit taskId is fail,{}", response);
            throw new BizRuntimeException(response);
        }
        return null;
    }

    @Data
    public static class TaskInfo {
        @JSONField(name = "task_id")
        private String taskId;

        @JSONField(name = "status")
        private String status;

        @JSONField(name = "file_id")
        private String fileId;

        @JSONField(name = "video_width")
        private int videoWidth;

        @JSONField(name = "video_height")
        private int videoHeight;
    }


}